<template>
  <el-select
    v-bind="$attrs"
    :value="value"
    filterable
    :remote-method="remoteMethod"
    remote
    clearable
    placeholder="请选择"
    :style="{width: width}"
    @input="input"
    @visible-change="open"
  >
    <el-option v-if="list.length==0" value="0" label="暂无数据" :disabled="true" />
    <el-option
      v-for="item in list"
      :key="item.id"
      :label="item.username"
      :value="item.id"
    />
    <div v-if="list.length!==0" style="text-align:center">
      <el-pagination
        :current-page.sync="page"
        :page-size="size"
        layout="prev, pager, next"
        :total="total"
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
      />
    </div>
  </el-select>
</template>

<script>
import request from '@/utils/request'

export default {
  name: 'JtSelect',
  model: {
    prop: 'value',
    event: 'input'
  },
  props: {
    value: [String, Number, Array],
    url: {
      type: String,
      default: ''
    },
    width: {
      type: String,
      default: '100%'
    }
  },
  data() {
    return {
      list: [],
      page: 1,
      size: 5
    }
  },
  created() {
    this.remoteMethod()
  },
  methods: {
    // 获取远程数据并赋值
    remoteMethod(query) {
      if (query !== '') {
        request({
          url: this.url,
          method: 'GET',
          params: {
            username: query,
            page: this.page - 1,
            size: this.size,
            total: 0
          }
        }).then(res => {
          if (res.content) {
            this.list = res.content.map(item => {
              item.username = item.username ? item.username : item.name
              item.enabled = item.enabled ? item.enabled : item.status
              return item
            }).filter(item => item.enabled === 1)
            this.total = res.totalElements
          }
        }).catch(e => {
          this.list = []
          this.$notify.error({
            title: '人员数据请求失败，请联系管理员',
            duration: 5000
          })
        })
      } else {
        this.list = []
      }
    },
    // 改变分页数值触发
    handleSizeChange(val) {
      this.limit = val
      this.remoteMethod()
    },
    handleCurrentChange(val) {
      this.page = val
      this.remoteMethod()
    },
    // 获取当前选中的值
    input(event) {
      const data = this.list.find(item => item.id === event)
      this.$emit('input', event)
      this.$emit('change', data)
    },
    open() {
      this.remoteMethod()
    }
  }
}
</script>

<style scoped>
  .crud-opts {
    display: -webkit-flex;
    display: flex;
    align-items: center;
  }
</style>
